<template>
  <!-- 导航 -->
    <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
        <el-col :span="24">
            <el-breadcrumb :separator-icon="ArrowRight">
                <el-breadcrumb-item>首页</el-breadcrumb-item>
                <el-breadcrumb-item>项目管理</el-breadcrumb-item>
                <el-breadcrumb-item>我的项目列表</el-breadcrumb-item>
            </el-breadcrumb>
        </el-col>
    </el-row>
  <!-- 搜索栏-->
    <el-row style="margin: 10px;background-color: ghostwhite;padding: 15px">
        <el-col :span="24">
            <el-form :model="projectQuery" inline>
                <el-form-item label="项目名称">
                    <el-input v-model="projectQuery.projectName"/>
                </el-form-item>
                <el-form-item label="项目状态">
                    <el-select style="width: 100px" v-model="projectQuery.projectStatus">
                        <el-option :value="0" label="全部"/>
                        <el-option :value="1" label="草稿"/>
                        <el-option :value="2" label="发布"/>
                        <el-option :value="3" label="暂停"/>
                        <el-option :value="4" label="意外"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                            v-model="startTimes"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                            v-model="endTimes"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button @click="loadProjects" type="primary">搜索</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
    <!-- 工具栏 -->
    <el-row style="margin: 0px 10px;background-color: ghostwhite;padding: 0px 10px">
        <el-col :span="24">
            <el-button-group>
                <el-button @click="showAddProjectWin" type="primary">新增</el-button>
                <el-button @click="toEdits" type="primary">编辑</el-button>
                <el-button @click="toDeletes" type="primary">删除</el-button>
                <el-button @click="toArchives" type="primary">归档</el-button>
                <el-button @click="toReleases" type="primary">发布</el-button>
            </el-button-group>
        </el-col>
    </el-row>
    <!-- 数据列表 -->
    <el-row style="margin: 0px 10px;padding: 0px 15px">
        <el-col :span="24">
            <el-table :data="projects" border stripe ref="projectTable">
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="projectId" label="#">
                    <template #default="scope">
                        <el-link @click="showDetail(scope.row.projectId)" type="success">{{
                            scope.row.projectId
                            }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="projectName" label="项目名称"/>
                <el-table-column prop="user.username" label="管理者"/>
                <el-table-column label="任务数量">
                    <template #default>
                        100
                    </template>
                </el-table-column>
                <el-table-column prop="projectStatus" label="项目状态">
                    <template #default="scope">
                        <el-tag type="info" v-if="scope.row.projectStatus == 1">草稿</el-tag>
                        <el-tag type="primary" v-else-if="scope.row.projectStatus == 2">发布</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.projectStatus == 3">归档</el-tag>
                        <el-tag type="warning" v-else-if="scope.row.projectStatus == 4">暂停</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.projectStatus == 5">意外</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始时间"/>
                <el-table-column prop="endTime" label="结束时间"/>
                <el-table-column prop="createTime" label="创建时间"/>
                <el-table-column label="操作" width="330">
                    <template #default="scope">
                        <el-button-group>
                            <template v-if="scope.row.userId == currUserId">
                                <el-button @click="toEdit(scope.row.projectId)" size="small" type="primary">编辑
                                </el-button>
                                <el-button @click="toArchive(scope.row)" size="small"
                                           :disabled="scope.row.projectStatus == 3" type="info">归档
                                </el-button>
                                <el-button @click="toDelete(scope.row)" size="small" type="danger">删除</el-button>
                            </template>
                            <el-button size="small" type="primary">任务</el-button>
                            <el-button size="small" type="primary">日历</el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>
    <!--  分页栏 -->
    <el-row style="margin: 0px 10px;padding: 0px 15px">
        <el-col :span="24">
            <el-pagination @change="changePage" background layout="prev, pager, next" :total="total"/>
        </el-col>
    </el-row>
  <!-- 新增项目的弹窗 -->
    <el-dialog v-model="projectAddWinDialogVisible"
               title="新增项目"
               width="50%"
    >
        <template #default>
            <el-form :model="newProject" label-width="auto">
                <el-form-item label="项目编号">
                    <el-input v-model="newProject.projectId"/>
                </el-form-item>
                <el-form-item label="项目名称">
                    <el-input v-model="newProject.projectName"/>
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开始时间">
                            <el-date-picker
                                    v-model="newProject.startTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束时间">
                            <el-date-picker
                                    v-model="newProject.endTime"
                                    type="date"
                                    value-format="YYYY-MM-DD"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-form-item label="项目描述">
                    <!-- 富文本编辑器的结构 -->
                    <div style="border: 1px solid #ccc">
                        <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editorRef"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                        />
                        <Editor
                                style="height: 500px; overflow-y: hidden;"
                                v-model="valueHtml"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="handleCreated"
                        />
                    </div>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelAddProject">取消</el-button>
                <el-button type="primary" @click="addProjectSubmit">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

  <!-- 详情子组件 -->
    <ProjectDetail :project-id="detailProjectId"/>
  <!-- 编辑子组件 -->
    <ProjectEdit :project-id="editProjectId" @editComplete="loadProjects()"/>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import projectRequest from "@/api/project.js";
import {useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import ProjectDetail from "@/views/project/project-detail.vue";
import ProjectEdit from "@/views/project/project-edit.vue";
import {ElMessageBox} from 'element-plus'
import login from "@/api/login.js";
// 封装搜索数据的对象
let projectQuery = ref({projectStatus: 0})
// 封装两个时间范围
let startTimes = ref([]);
let endTimes = ref([]);
// 查询的项目列表
let projects = ref([]);
// 总条数，默认0
let total = ref(0);
// 当前页码，默认1
let curPage = ref(1);
// 当前登录用户的编号
let currUserId = ref();
let router = useRouter();
// 新增项目的弹窗标记
let projectAddWinDialogVisible = ref(false);
// 保存新增项的表单的数据
let newProject = ref({});

let detailProjectId = ref(-1);
let editProjectId = ref(-1);

let projectTable = ref(null);

function showDetail(projectId) {
    detailProjectId.value = projectId;
}

function toEdit(projectId) {
    editProjectId.value = projectId;
}


// 富文本编辑器相关的属性
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML ，如果我们修改了内容，这里会跟着变化
const valueHtml = ref('');
// 工具栏配置
const toolbarConfig = {}
// 编辑器配置
const editorConfig = {placeholder: '请输入项目描述...'}


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

/**
 * 工具栏批量发布按钮事件
 */
function toReleases(){
    let selectedRows = projectTable.value.getSelectionRows();
    if (selectedRows.length == 0){
        ElMessage({
            type:"warning",
            message:"你没有选中任何数据"
        });
        return;
    }
    ElMessageBox.confirm(
        '您确定要将选中的项目发布吗？',
        '提示',
        {
            confirmButtonText: '是的',
            cancelButtonText: '点错了',
            type: 'warning',
        }
    ).then(() => {
        let noCurUserProjectNames = [];
        let projectIds = [];
        selectedRows.forEach(row=>{
            if(row.userId != currUserId.value){
                noCurUserProjectNames.push(row.projectName);
            }
            projectIds.push(row.projectId);
        })
        if(noCurUserProjectNames.length > 0){
            ElMessage({
                type:"warning",
                message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有发布权限"
            });
            return;
        }
        projectRequest.releases(projectIds,res=>{
            if(res.code == 200){
                ElMessage({
                    type:"success",
                    message:"成功发布[" + res.data + "]条数据"
                })
                loadProjects();
            }else{
                ElMessage({
                    type:"warning",
                    message:"发布失败"
                })
            }
        });
    }).catch(()=>{});
}

/**
 * 工具栏批量归档按钮事件
 */
function toArchives(){
    let selectedRows = projectTable.value.getSelectionRows();
    if (selectedRows.length == 0){
        ElMessage({
            type:"warning",
            message:"你没有选中任何数据"
        });
        return;
    }
    ElMessageBox.confirm(
        '您确定要将选中的项目归档吗？',
        '提示',
        {
            confirmButtonText: '是的',
            cancelButtonText: '点错了',
            type: 'warning',
        }
    ).then(() => {

        let noCurUserProjectNames = [];
        let draftProjectName = []
        let projectIds = [];
        selectedRows.forEach(row=>{
            if(row.userId != currUserId.value){
                noCurUserProjectNames.push(row.projectName);
            }
            if(row.projectStatus == 1){
                draftProjectName.push(row.projectName);
            }
            projectIds.push(row.projectId);
        })
        if(noCurUserProjectNames.length > 0){
            ElMessage({
                type:"warning",
                message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，你没有归档权限"
            });
            return;
        }
        if(draftProjectName.length > 0){
            ElMessage({
                type:"warning",
                message:"您选中的项目中，有以下项目[" + draftProjectName.join(",") + "]属于草稿状态，不能执行归档操作"
            });
            return;
        }
        projectRequest.archives(projectIds,res=>{
            if(res.code == 200){
                ElMessage({
                    type:"success",
                    message:"成功归档[" + res.data + "]条数据"
                })
                loadProjects();
            }else{
                ElMessage({
                    type:"warning",
                    message:"归档失败"
                })
            }
        });
    }).catch(()=>{});
}
/**
 * 工具栏批量删除按钮事件
 */
function toDeletes(){
    let selectedRows = projectTable.value.getSelectionRows();
    if (selectedRows.length == 0){
        ElMessage({
            type:"warning",
            message:"你没有选中任何数据"
        });
        return;
    }
    ElMessageBox.confirm(
        '您确定要删除选中的项目吗？',
        'Warning',
        {
            confirmButtonText: '是的',
            cancelButtonText: '点错了',
            type: 'warning',
        }
    ).then(() => {

        let noCurUserProjectNames = [];
        let projectIds = [];
        selectedRows.forEach(row=>{
            if(row.userId != currUserId.value){
                noCurUserProjectNames.push(row.projectName);
            }
            projectIds.push(row.projectId);
        })
        if(noCurUserProjectNames.length > 0){
            ElMessage({
                type:"warning",
                message:"您选中的项目中，有以下项目[" + noCurUserProjectNames.join(",") + "]并非您管理的，不能删除"
            });
            return;
        }
        projectRequest.deletesProject(projectIds,res=>{
            if(res.code == 200){
                ElMessage({
                    type:"success",
                    message:"成功删除[" + res.data + "]条数据"
                })
                loadProjects();
            }else{
                ElMessage({
                    type:"warning",
                    message:"删除失败"
                })
            }
        });
    }).catch(()=>{});
}
/**
 * 工具栏编辑按钮事件
 */
function toEdits(){
    let selectedRows = projectTable.value.getSelectionRows();
    if(selectedRows.length > 1){
        ElMessage({
            type:"warning",
            message:"编辑只能编辑一条数据"
        });
    }else if (selectedRows.length == 0){
        ElMessage({
            type:"warning",
            message:"你没有选中任何数据"
        });
    }else if(selectedRows[0].userId != currUserId.value){
        ElMessage({
            type:"warning",
            message:"你只能编辑你自己管理的项目"
        });
    }else{
        toEdit(selectedRows[0].projectId);
    }
}

/**
 * 行归档按钮事件
 */
function toArchive(project) {
    ElMessageBox.confirm(
        '您确定要将项目[' + project.projectName + "]归档吗？",
        'Warning',
        {
            confirmButtonText: '是的',
            cancelButtonText: '点错了',
            type: 'warning',
        }
    ).then(() => {
        projectRequest.archiveProject(project.projectId,res=>{
            ElMessage({
                type:"success",
                message:"操作完成"
            });
            loadProjects();
        })
    }).catch(()=>{});
}

/**
 * 行删除按钮事件
 * @param projectId
 */
function toDelete(project) {
    ElMessageBox.confirm(
        '您确定要将项目[' + project.projectName + "]删除吗？",
        'Warning',
        {
            confirmButtonText: '是的',
            cancelButtonText: '点错了',
            type: 'warning',
        }
    ).then(() => {
        projectRequest.deleteProject(project.projectId,res=>{
            ElMessage({
                type:"success",
                message:"操作完成"
            });
            loadProjects();
        })
    }).catch(()=>{});
}

/**
 * 工具栏新增项目按钮事件
 */
function showAddProjectWin() {
    projectAddWinDialogVisible.value = true;
}

/**
 * 取消新增项目的按钮事件
 */
function cancelAddProject() {
    // 将newProject置空
    newProject = ref({});
    // 关闭弹窗
    projectAddWinDialogVisible.value = false;
}

/**
 * 新增项目的提交按钮事件
 */
function addProjectSubmit() {
    newProject.value.projectDesc = valueHtml.value;
    newProject.value.userId = currUserId.value;
    projectRequest.saveProject(newProject.value, res => {
        if (res.code == 200) {
            ElMessage({
                type: "success",
                message: "添加成功"
            });
            cancelAddProject();
            loadProjects()
        } else if (res.code == 300) {
            ElMessage({
                type: "warning",
                message: "项目编号重复"
            });
        } else {
            ElMessage({
                type: "warning",
                message: "项目添加失败"
            });
        }
    })
}

/**
 * 加载项目列表
 */
function loadProjects() {
    //处理查询条件，处理时间范围
    if (startTimes.value[0]) {
        projectQuery.value.startTimeBegin = startTimes.value[0];
    }
    if (startTimes.value[1]) {
        projectQuery.value.startTimeEnd = startTimes.value[1];
    }
    if (endTimes.value[0]) {
        projectQuery.value.endTimeBegin = endTimes.value[0];
    }
    if (endTimes.value[1]) {
        projectQuery.value.endTimeBegin = startTimes.value[1];
    }
    projectQuery.value.userId = currUserId.value;
    console.log(currUserId.value)
    console.log(projectQuery.value)
    // 调用API来查询项目列表
    projectRequest.loadProjects(projectQuery.value, curPage.value, 10, res => {
        // 这里的res就是后端返回的结果
        // 总条数赋值
        total.value = res.data.total;
        // 将查询的列表赋值给projects
        projects.value = res.data.list;
    })
}

// 分页事件
function changePage(value) {
    curPage.value = value;
    loadProjects();
}

onMounted(() => {

    // 从localStorage中获取用户编号
    currUserId.value = localStorage.getItem("userId");
    loadProjects();
    if (currUserId.value == undefined || currUserId.value == '') {
        // 进入登录页面
        router.push("/");
    }
})
</script>

<style scoped>

</style>